<?php

function _output($d=[], $c=200, $m=''){
    echo json_encode(['c'=>$c, 'd'=>$d, 'm'=>$m], JSON_UNESCAPED_UNICODE);
    exit;
}
/*
 * HTTP GET Request
*/
function get($url, $param = null) {
    if($param != null) {
        $query = http_build_query($param);
        $url = $url . '?' . $query;
    }
    $ch = curl_init();
    if(stripos($url, "https://") !== false){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    $content = curl_exec($ch);
    $status = curl_getinfo($ch);
    curl_close($ch);
    if(intval($status["http_code"]) == 200) {
        return $content;
    }else{
        return false;
    }
}

/*
 * HTTP POST Request
*/
function post($url, $params) {
    $ch = curl_init();
    if(stripos($url, "https://") !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $content = curl_exec($ch);
    $status = curl_getinfo($ch);
    curl_close($ch);
    if(intval($status["http_code"]) == 200) {
        return $content;
    } else {
        return $content;
        echo $status["http_code"];

        return false;
    }
}

function encodeFileName($str) {
    $pathinfo = pathinfo($str);
    return dirname($str) . '/' . rawurlencode(basename($str));
}
function setUpUrl($url) {
    if (empty($url))
        return '';
    if (substr_count($url, 'http://'))
        return $url;
    $url = str_replace("&amp;", "&", $url);
    return C('YOU_PAI_YUN') . encodeFileName($url);
}

function uploadYPPhoto($file, $rootPath = 'Uploads') {
    $root_path = './' . $rootPath . '/';
    $config = array(
        'rootPath' => $root_path, //保存根路径
//        'mimes' => array('image/gif', 'image/jpeg', 'image/png'), //允许上传的文件MiMe类型
        'maxSize' => 2097152, //上传的文件大小限制 (0-不做限制)
        'exts' => array(), //允许上传的文件后缀
        'saveName' => '', //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
        'replace' => true
    );
    $mm = new \Think\Upload($config);
    $m = $mm->uploadOne($file);
    if ($m) {
        return array('status' => 1, 'url' => setUpUrl('/' . $rootPath . '/' . $m['savepath'] . $m['savename']));
    } else {
        return array('status' => 0, 'msg' => $mm->getError());
    }
}


function uploadPhoto($file, $rootPath = 'Uploads') {
    $root_path = './' . $rootPath . '/';
    $config = array(
        'rootPath' => $root_path, //保存根路径
//        'mimes' => array('image/gif', 'image/jpeg', 'image/png'), //允许上传的文件MiMe类型
        'maxSize' => 2097152, //上传的文件大小限制 (0-不做限制)
        'exts' => array(), //允许上传的文件后缀
        'saveName' => '', //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
        'replace' => true
    );
    $mm = new \Think\Upload($config,'Local');
    $m = $mm->uploadOne($file);
    if ($m) {
        return array('status' => 1, 'url' => '/' . $rootPath . '/' . $m['savepath'] . $m['savename']);
    } else {
        return array('status' => 0, 'msg' => $mm->getError());
    }
}

function getWXImg($img,$default_img=""){
    if($img){
       return C('YOU_PAI_YUN').$img;
    }else{
        return $default_img;
    }
}

function is_weixin(){
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return true;
    }
    return false;
}

/**
 * DEBUG 打印数据格式化函数
 * @param mixed $result
 */
function _debug($result) {
    echo "<pre>";
    print_r($result);
    echo "</pre>";
    exit();
}

/**
 * 执行curl
 * @param type $url
 * @param type $post_data
 * @param type $charsetfrom
 * @param type $charsetto
 * @param type $timeout
 * @return type
 */
function getRemoteData($url,$post_data=[], $charsetfrom="",$charsetto="",$timeout=60){
    $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;
    $ch  = @curl_init();
    $a   = array(" ");
    $b   = array("%20");
    $url = str_replace($a, $b, $url);
    @curl_setopt($ch, CURLOPT_URL, $url);
    @curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    @curl_setopt($ch,CURLOPT_HEADER,0);
    @curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    if(count($post_data)>0)
    {
        @curl_setopt($ch, CURLOPT_POST, 1 );
        @curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }
    if ($ssl)
    {
        @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1 );
        @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    }   
    @curl_setopt_array($ch, $opt=[]);
    $contents = @curl_exec($ch);
    $status = curl_getinfo($ch);
    @curl_close($ch);
    if( $charsetfrom!="" && $charsetto!="" ){
        $contents = iconv($charsetfrom, $charsetto,$contents);
    }

    return $contents;
}

function _log($msg,$filename='') {
    if(is_array($msg)){
        $msg = var_export($msg, TRUE);
    }
    // 每日日志记录
    $time = date('Y-m-d', time());
    $savepath='/Application/Common/Log/'.$filename;
    _mkdirs($savepath,".");
    $newfile = '.'.$savepath.'/'.$time.'.txt';
    $handle = fopen($newfile, "a+"); /* 根据需要更改这里的参数 */
    $c = date('Y-m-d H:i:s', time()) . " " . $msg . "\r\n";
    $contents = fwrite($handle, $c);
    fclose($handle);
}

function __log($filename='dingdan',$txt) {
    if(is_array($txt)){
        $txt = var_export($txt, TRUE);
    }
    // 每日日志记录
    $time = date('Y-m-d', time());
    $savepath='/Public/log/'.$filename;
    _mkdirs($savepath,DocumentRoot);
    $newfile = '.'.$savepath.'/'.$time.'.txt';
    $handle = fopen($newfile, "a+"); /* 根据需要更改这里的参数 */
    $c = date('Y-m-d H:i:s', time()) . " " . $txt . "\r\n";
    $contents = fwrite($handle, $c);
    fclose($handle);
}

//建多级文件夹
function _mkdirs($dir,$rootpath='.'){
    if(!$rootpath)
        return false;
    if($rootpath=='.')
        $rootpath=realpath($rootpath);
    $forlder=explode('/',$dir);
    $path='';
    for($i=0;$i<count($forlder);$i++){
        if($current_dir=trim($forlder[$i])){
            if($current_dir=='.')
                continue;
            $path.='/'.$current_dir;
            if($current_dir=='..'){
                continue;
            }
            if(file_exists($rootpath.$path)){
                @chmod($rootpath.$path,0777);
            }else{
                if(!_mkdir($rootpath.$path)){
                    return false;
                }
            }
        }
    }
    return true;
}
//建文件夹
function _mkdir($dir){
    if(file_exists($dir))
        return true;
    $u=umask(0);
    $r=@mkdir($dir,0777);
    umask($u);
    return $r;
}
function https_request($url,$data,$type){
    if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $data=json_encode($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

function mobile_status($status){
    //$arr = ['未联系','正常','未接','拒接','停机','电话空号','中途挂机'];
    $arr = [
        1=>'正常',
        2=>'停机',
        3=>'空号',
        4=>'未接',
        5=>'拒接',
        6=>'中途挂机'
    ];
    return $arr[$status];
}

function follow_mode($status){
    $arr = [
        1=>'手机',
        2=>'座机',
        3=>'微信',
        4=>'短信',
    ];
    return $arr[$status];
}

function linkman_role($role){
    $arr = [
        100 => '老板',
        200 => '采购员',
        300 => '销售',
        999 => '其他'
    ];
    return $arr[$role];
}

function mobile_no_hidden($str) {
    if(!$str) return '';
    if(!(strpos('*',$str)>-1)) {
        $begin = 3;
        $end = 7;
        $char = '****';
        $fstStr = substr($str, 0, $begin);
        $lstStr = substr($str, $end, strlen($str));
        return $fstStr . $char . $lstStr;
    }
    return $str;
}

function name_hidden($str) {
    if(!$str) return '';
    if(!(strpos('*',$str)>-1)) {
        $begin = 1;
        $char = '';
        for ($i=1;$i<mb_strlen($str);$i++) {
            $char .= '*';
        }

        $fstStr = _substr($str, $begin,'');
        return $fstStr . $char;
    }
    return $str;
}

function clear_kongge($str) {
    return str_replace(array(
        '&nbsp;',
        ' ',
        "　",
        "\t",
        "\r",
        "\n"
    ), '', $str);
}

function _substr($string, $length, $dot = '...', $ClearHtml = true, $charset = 'utf-8') {
    if (mb_strlen($string) <= $length) {
        return $string;
    }
    if ($ClearHtml) {
        $string = str_replace(array(
            '&amp;',
            '&quot;',
            '&lt;',
            '&gt;',
            '&nbsp;'
        ), array(
            '&',
            '"',
            '<',
            '>',
            ' '
        ), $string);
        $string = strip_tags(clear_kongge($string));
    }
    $string = preg_replace('/([\s]{2,})/', '', $string);
    $strcut = mb_substr($string, 0, $length, $charset);
    return $strcut . (strlen($string) > strlen($strcut) ? $dot : '');
}

/**
 * 精准匹配客户数
 * @param $total
 * @return float
 */
function jztotal($total){
    if ($total < 10000) {
        $total = $total * 0.7;
    } elseif ($total >= 10000 && $total <= 70000) {
        $total = $total * 0.6;
    } elseif ($total > 70000 && $total <= 100000) {
        $total = $total * 0.4;
    } elseif ($total > 100000 && $total <= 200000) {
        $total = $total * 0.25;
    } elseif ($total > 200000 && $total <= 400000) {
        $total = $total * 0.16;
    } elseif ($total > 400000 && $total <= 800000) {
        $total = $total * 0.13;
    } elseif ($total > 800000 && $total <= 1200000) {
        $total = $total * 0.08;
    } elseif ($total > 1200000 && $total <= 1600000) {
        $total = $total * 0.06;
    } elseif ($total > 1600000 && $total <= 2000000) {
        $total = $total * 0.07;
    } elseif ($total > 2000000) {
        $total = $total * 0.08;
    }
    return ceil($total);
}

function output($d=[],$c=200,$m=''){
    echo json_encode(['c'=>$c,'d'=>$d,'m'=>$m], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 两个日期之间的所有日期
 * @param $start
 * @param $end
 */
function prDates($start,$end){
    $dt_start = strtotime($start);
    $dt_end = strtotime($end);
    while ($dt_start<=$dt_end){
        $res[] = date('Ymd',$dt_start);
        $dt_start = strtotime('+1 day',$dt_start);
    }
    $res[] = date('Ymd',$end);
    return $res;
}

/**
 * 验证日期是否是节假日
 * @param $date 日期：多个日期用逗号分割
 * @return bool|string：单个日期返回数字（0、工作日1、周末2、节日），多个日期返回json字符串
 */
function checkIsHoliday($date){
    if($date){
        $url = 'http://tool.bitefu.net/jiari/';
        $push_data = ['d' => $date];
        $rs = getRemoteData($url, $push_data);
        return $rs;
    }else{
        return false;
    }
}

/**
 * 判断是否超过三个工作日
 * @param $date
 */
function checkIsExpire($date){
    $three_days_ago = strtotime(date('Y-m-d H:i:s')." -3 day");
    $eleven_days_ago = strtotime(date('Y-m-d H:i:s')." -11 day");
    $time = strtotime($date);
    if($time > $three_days_ago){//三天内
        return false;
    }elseif($time <= $eleven_days_ago){//11天后
        return true;
    }
    //3-11天
    $all_date = prDates($date, date('Y-m-d'));
    $holiday_res = checkIsHoliday(implode(',', $all_date));
    $holiday_res = json_decode($holiday_res, true);
    foreach ($holiday_res as $k=>&$v) {
        if(in_array($k,['20180102'])) {
            $v = 0;
            unset($v);
        }
    }
    $result = array_count_values($holiday_res);//统计工作日数
    //_debug($holiday_res);
    if($result[0]==3){//判断时间点
        if(date('H:i:s')<date('H:i:s',$time)){
            return false;
        }else{
            return true;
        }
    }else if($result[0]<3){
        return false;
    }
    return true;
}
/**
 *获取最近20天的假日情况
 */
function getHoliday(){
    $is_expire_day = strtotime(date('Y-m-d H:i:s')." -20  day");
    $all_date = prDates(date('Y-m-d H:i:s',$is_expire_day), date('Y-m-d'));
    $holiday_res = checkIsHoliday(implode(',', $all_date));
    $holiday_res = json_decode($holiday_res, true);
    return $holiday_res;
}
/**
 * 判断创建时间距离当前时间是多少个工作日
 * @param $date
 */
function newCheckIsExpire($date,$holidays){
    $days = 0;
    $key = array_keys($holidays);
    if($key[0] > $date){
        return 99;
    }
    foreach ($holidays as $key => $value ) {
        if($key > $date && $value == 0){
            $days ++;
        }
    }
    return $days;
}
/**
 * 判断是否超过三个工作日
 * @param $date
 * @param $expire_day
 */
function checkIsExpireDay($date,$expire_day=3){
    $days_ago = strtotime(date('Y-m-d H:i:s')." -".$expire_day." day");
    $n_days_ago = strtotime(date('Y-m-d H:i:s')." -8 day -".$expire_day." day");
    $time = strtotime($date);
    if($time > $days_ago){//n天内
        return 0;
    }elseif($time <= $n_days_ago){//m天后
        return 1;
    }
    //n-m天
    $all_date = prDates($date, date('Y-m-d'));
    $holiday_res = checkIsHoliday(implode(',', $all_date));
    $holiday_res = json_decode($holiday_res, true);
    foreach ($holiday_res as $k=>&$v) {
        if(in_array($k,['20180102'])) {
            $v = 0;
            unset($v);
        }
    }
    $result = array_count_values($holiday_res);//统计工作日数
    if($result[0]+1==$expire_day){//判断时间点
        if(date('H:i:s')<date('H:i:s',$time)){
            return 0;
        }else{
            return 1;
        }
    }else if($result[0]+1<$expire_day){
        return 0;
    }
    return 1;
}
/**
 * 判断是否超过三个工作日
 * @param $date
 * @param $expire_day
 */
function new_checkIsExpireDay($date,$expire_day=3){
    $days_ago = strtotime(date('Y-m-d H:i:s')." -".$expire_day." day");
    $n_days_ago = strtotime(date('Y-m-d H:i:s')." -8 day -".$expire_day." day");
    $time = strtotime($date);
    if($time > $days_ago){//n天内
        return 0;
    }elseif($time <= $n_days_ago){//m天后
        return 1;
    }
    //n-m天
    $all_date = prDates($date, date('Y-m-d'));
    $holiday_res = checkIsHoliday(implode(',', $all_date));
    $holiday_res = json_decode($holiday_res, true);
    $now_date = date('Ymd',$time);
    foreach ($holiday_res as $k=>&$v) {
        if(in_array($k,['20180102'])) {
            $v = 0;
            unset($v);
        }
        if(in_array($k,[$now_date])){
            unset($holiday_res[$k]);
        }
    }
    $result = array_count_values($holiday_res);//统计工作日数
    if(isset($result[0])){
        if($result[0] > $expire_day){//判断时间点
            return 1;
        }else{
            return 0;
        }
    }else{
        return 0;
    }
    return 1;
}

/**
 * 营销宝正式版本
 * @return array
 */
function version(){
    $version = [
        1=>'黄金增强版',
        2=>'白金增强版',
        3=>'钻石增强版',
        4=>'经典版',
        5=>'全能版',
        6=>'试用小二',
        7=>'金牌掌柜',
        8=>'全职管家',
        9=>'律师：区域首席',
        10=>'律师：城市首席',
        11=>'营销宝城市全行业首席',
        12=>'营销宝首席食堂黄金版',
        13=>'营销宝首席食堂白金版',
        14=>'营销宝首席食堂钻石版'
    ];
    return $version;
}

//解析URL参数
function parseUrlParam($query){
    $queryArr = explode('&', $query);
    $params = array();
    if($queryArr[0] !== ''){
        foreach( $queryArr as $param ){
            list($name, $value) = explode('=', $param);
            $params[urldecode($name)] = urldecode($value);
        }
    }
    return $params;
}

//两个时间相差多少天
function diffBetweenTwoDays ($day1, $day2)
{
  $second1 = strtotime($day1);
  $second2 = strtotime($day2);
   
  if ($second1 < $second2) {
    $tmp = $second2;
    $second2 = $second1;
    $second1 = $tmp;
  }
  return ($second1 - $second2) / 86400;
}